package com.captain.controller;

import com.captain.common.Result;
import com.captain.entity.po.User;
import com.captain.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 处理登录，注册，退出
 */
@Controller
public class AuthController {
    @Autowired
    UserService userService;

    @GetMapping("/login")
    public String login(){
        return "user/login";
    }

    @PostMapping("/doLogin")
    @ResponseBody
    public Result doLogin(HttpServletRequest req, User user, String vercode){
        //从数据库查询该账号的用户
        User dbUser=userService.getUserByEmail(user.getEmail());
        if(dbUser!=null){
            if(dbUser.getPass().equals(user.getPass())){
                //把user的数据设置到session中
                req.getSession().setAttribute("user",dbUser);
                //指定登录成功之后跳转到的页面
                return Result.success("登录成功",null).setAction("/index");
            }else{
                return Result.fail("密码错误");
            }
        }else{
            return Result.fail("用戶不存在");
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest req){
        //清空用户信息
        req.getSession().setAttribute("user",null);
        return "user/login";
    }

    @GetMapping("/register")
    public String register(){
        return "user/reg";
    }

    @ResponseBody
    @PostMapping("/doRegister")
    public Result doRegister(HttpServletRequest req, User user, String vercode){
        //先判断验证码
        String codeText = (String)req.getSession().getAttribute("KAPTCHA_SESSION_KEY");
        //验证码不区分大小写
        if(codeText.toLowerCase().equals(vercode.toLowerCase())){
            //开始注册
            if(userService.addUser(user)>0){
                return Result.success("注册成功",null).setAction("/login");
            }else{
                return Result.fail("注册失败");
            }
        }else{
            return Result.fail("验证码错误");
        }
    }

}
